package cn.lccabc.login.controller;

import cn.lccabc.user.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by L on 2018/4/8.
 */
@Controller
@RequestMapping(value = "login")
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "index")
    public String index() {
        return "index";
    }

    @RequestMapping(value = "check")
    @ResponseBody
    public String checkLogin(HttpServletRequest request) {
//        String username = request.getParameter("username");
//        String password = request.getParameter("password");
//        User user = userService.findUserByUserName(username);
//        if (user != null){
//            if (SecurityUtils.checkPassword(password,user.getPassword())){
//                request.getSession().setAttribute("userinfo",user);
//                return "login_succeed";
//            } else {
//                return "login_fail";
//            }
//        } else {
//            return "login_fail";
//        }
        //shiro重写后
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        org.apache.shiro.subject.Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            SecurityUtils.getSubject().getSession().setTimeout(1800000);
        } catch (Exception e){
            return "login_fail";
        }
        return "login_succeed";
    }

    @RequestMapping(value = "logout")
    @ResponseBody
    public String logout(HttpSession session){
        session.invalidate();
        return "logout";
    }

}
